package org.fluidripple.socket.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fluidripple.socket.inbound.ClientEventHandler;
import org.fluidripple.socket.operation.AutomationOperation;
import org.fluidripple.socket.operation.ChannelOperation;
import org.fluidripple.socket.session.Session;
import org.fluidripple.socket.session.SessionManager;
import org.fluidripple.socket.stickhalf.DelimiterBasedFrameDecoderImpl;
import org.fluidripple.socket.stickhalf.FixedLengthDecoderImpl;
import org.fluidripple.socket.wrapper.DataWrapper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceStartCollectProtocol extends Protocol{

    private final DeviceDataCollectProtocol deviceDataCollectProtocol;

    @Override
    public void writer(Channel channel) {
        Session session = SessionManager.getSession(channel);
        session.setProtocol(this);
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(ByteBufUtil.decodeHexDump("F0C103A0A3"));
        channel.writeAndFlush(buf);
        ChannelOperation.replaceChannelHandler(channel,ClientEventHandler.name, FixedLengthDecoderImpl.name,new FixedLengthDecoderImpl(5));
    }

    @Override
    public void toDecode(DataWrapper dataWrapper) {
        ByteBuf buf = dataWrapper.getBuf();
        String hexDump = ByteBufUtil.hexDump(buf);
        Session session = dataWrapper.getSession();
        log.info("开始采集：{} 设备数据，设备返回指令码：{}",session.getDeviceSerializable(),hexDump);
        session.setCollectData(true);
        session.setProtocol(deviceDataCollectProtocol);
        AutomationOperation.delete(session.getChannel());
        ChannelOperation.replaceChannelHandler(session.getChannel(),ClientEventHandler.name, FixedLengthDecoderImpl.name,
                new DelimiterBasedFrameDecoderImpl(
                15, ByteBufAllocator.DEFAULT.buffer().writeBytes(
                        ByteBufUtil.decodeHexDump(DelimiterBasedFrameDecoderImpl.DELIMITER)
                )
        ));
    }
}
